import React, { useState } from 'react';
import { motion } from 'motion/react';
import { Button } from '../../components/ui/button';
import { Card, CardContent, CardHeader } from '../../components/ui/card';
import { Badge } from '../../components/ui/badge';
import { 
  ArrowLeft, 
  Download, 
  Printer, 
  Edit,
  User,
  Calendar,
  CheckCircle,
  AlertCircle,
  Save
} from 'lucide-react';

interface MedicalRecordPageProps {
  onGoBack: () => void;
  onReturnHome: () => void;
}

interface MedicalRecord {
  patientInfo: {
    name: string;
    age: number;
    gender: string;
    id: string;
    phone: string;
  };
  visitInfo: {
    date: string;
    time: string;
    department: string;
    doctor: string;
    doctorTitle: string;
  };
  symptoms: {
    mainComplaint: string;
    presentIllness: string;
    pastHistory: string;
  };
  diagnosis: {
    preliminary: string;
    confirmed: boolean;
    doctorConfirmed: boolean;
    confirmedBy?: string;
    confirmedAt?: string;
  };
}

export function MedicalRecordPage({ onGoBack, onReturnHome }: MedicalRecordPageProps) {
  const [isEditing, setIsEditing] = useState(false);
  const [savedNotification, setSavedNotification] = useState(false);

  const [record] = useState<MedicalRecord>({
    patientInfo: {
      name: '张先生',
      age: 35,
      gender: '男',
      id: '320102********1234',
      phone: '138****5678'
    },
    visitInfo: {
      date: new Date().toLocaleDateString('zh-CN'),
      time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
      department: '消化内科',
      doctor: '李明',
      doctorTitle: '主任医师'
    },
    symptoms: {
      mainComplaint: '反复胃痛、反酸3周',
      presentIllness: `患者3周前无明显诱因出现胃痛，疼痛位于上腹部，呈阵发性钝痛，伴有反酸、嗳气，进食后症状加重，空腹时症状减轻。无恶心、呕吐，无发热，无腹泻。患者自服胃药后症状稍有缓解，但仍反复发作。睡眠、精神可，食欲较前减退，大小便正常，体重无明显变化。`,
      pastHistory: '既往体健，否认高血压、糖尿病等慢性疾病史，否认手术史，否认药物过敏史。'
    },
    diagnosis: {
      preliminary: '1. 慢性胃炎？\n2. 胃食管反流病？',
      confirmed: false,
      doctorConfirmed: false
    }
  });

  const handleSave = () => {
    setSavedNotification(true);
    setTimeout(() => setSavedNotification(false), 3000);
  };

  const handleDownload = () => {
    // 模拟下载功能
    console.log('下载病历');
  };

  const handlePrint = () => {
    // 模拟打印功能
    window.print();
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-green-50">
      {/* 顶部操作区 */}
      <motion.div 
        className="bg-white shadow-sm border-b px-4 py-4"
        initial={{ y: -100 }}
        animate={{ y: 0 }}
      >
        <div className="flex items-center justify-between max-w-4xl mx-auto">
          <div className="flex items-center space-x-4">
            <Button
              variant="ghost"
              onClick={onGoBack}
              className="text-gray-600"
            >
              <ArrowLeft className="w-4 h-4 mr-2" />
              返回修改
            </Button>
            <h1 className="text-lg font-semibold text-gray-900">病历预览</h1>
          </div>
          
          <div className="flex items-center space-x-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setIsEditing(!isEditing)}
              className="text-blue-600 border-blue-200"
            >
              <Edit className="w-4 h-4 mr-1" />
              编辑
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={handleDownload}
            >
              <Download className="w-4 h-4 mr-1" />
              下载
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={handlePrint}
            >
              <Printer className="w-4 h-4 mr-1" />
              打印
            </Button>
          </div>
        </div>
      </motion.div>

      {/* 保存通知 */}
      {savedNotification && (
        <motion.div
          className="fixed top-20 right-4 z-50 bg-green-500 text-white px-4 py-2 rounded-lg shadow-lg flex items-center"
          initial={{ opacity: 0, x: 100 }}
          animate={{ opacity: 1, x: 0 }}
          exit={{ opacity: 0, x: 100 }}
        >
          <CheckCircle className="w-4 h-4 mr-2" />
          已保存
        </motion.div>
      )}

      <div className="px-4 py-8">
        <div className="max-w-4xl mx-auto">
          {/* 病历内容区 */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5 }}
          >
            <Card className="bg-white shadow-xl border-2 border-dashed border-gray-200 min-h-[800px]">
              <CardContent className="p-8">
                {/* 病历头部 */}
                <div className="text-center mb-8 border-b-2 border-gray-200 pb-6">
                  <h1 className="text-2xl font-bold text-gray-900 mb-2">门诊病历</h1>
                  <p className="text-gray-600">医联智导系统 · 智能生成</p>
                </div>

                {/* 患者基本信息 */}
                <div className="grid grid-cols-2 gap-6 mb-8 p-4 bg-gray-50 rounded-lg">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">姓名</label>
                    <p className="text-gray-900">{record.patientInfo.name}</p>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">性别/年龄</label>
                    <p className="text-gray-900">{record.patientInfo.gender} / {record.patientInfo.age}岁</p>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">就诊日期</label>
                    <p className="text-gray-900 flex items-center">
                      <Calendar className="w-4 h-4 mr-1" />
                      {record.visitInfo.date} {record.visitInfo.time}
                    </p>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">科室/医生</label>
                    <p className="text-gray-900 flex items-center">
                      <User className="w-4 h-4 mr-1" />
                      {record.visitInfo.department} / {record.visitInfo.doctor} {record.visitInfo.doctorTitle}
                    </p>
                  </div>
                </div>

                {/* 主诉 */}
                <div className="mb-6">
                  <h3 className="text-lg font-semibold text-gray-900 mb-3 flex items-center">
                    主诉
                    {isEditing && <Edit className="w-4 h-4 ml-2 text-blue-500" />}
                  </h3>
                  <div className={`p-4 rounded-lg ${isEditing ? 'bg-blue-50 border-2 border-blue-200' : 'bg-gray-50'}`}>
                    {isEditing ? (
                      <textarea 
                        className="w-full bg-transparent resize-none outline-none"
                        defaultValue={record.symptoms.mainComplaint}
                        rows={2}
                      />
                    ) : (
                      <p className="text-gray-800 leading-relaxed">{record.symptoms.mainComplaint}</p>
                    )}
                  </div>
                </div>

                {/* 现病史 */}
                <div className="mb-6">
                  <h3 className="text-lg font-semibold text-gray-900 mb-3 flex items-center">
                    现病史
                    {isEditing && <Edit className="w-4 h-4 ml-2 text-blue-500" />}
                  </h3>
                  <div className={`p-4 rounded-lg ${isEditing ? 'bg-blue-50 border-2 border-blue-200' : 'bg-gray-50'}`}>
                    {isEditing ? (
                      <textarea 
                        className="w-full bg-transparent resize-none outline-none"
                        defaultValue={record.symptoms.presentIllness}
                        rows={6}
                      />
                    ) : (
                      <p className="text-gray-800 leading-relaxed">{record.symptoms.presentIllness}</p>
                    )}
                  </div>
                </div>

                {/* 既往史 */}
                <div className="mb-6">
                  <h3 className="text-lg font-semibold text-gray-900 mb-3">既往史</h3>
                  <div className="p-4 bg-gray-50 rounded-lg">
                    <p className="text-gray-800 leading-relaxed">{record.symptoms.pastHistory}</p>
                  </div>
                </div>

                {/* 初步诊断 */}
                <div className="mb-6">
                  <div className="flex items-center justify-between mb-3">
                    <h3 className="text-lg font-semibold text-gray-900">初步诊断</h3>
                    <div className="flex items-center space-x-2">
                      {record.diagnosis.doctorConfirmed ? (
                        <Badge className="bg-green-100 text-green-800 flex items-center">
                          <CheckCircle className="w-3 h-3 mr-1" />
                          医生已确认
                        </Badge>
                      ) : (
                        <Badge variant="outline" className="bg-yellow-50 text-yellow-800 border-yellow-200 flex items-center">
                          <AlertCircle className="w-3 h-3 mr-1" />
                          待医生确认
                        </Badge>
                      )}
                    </div>
                  </div>
                  <div className="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
                    <pre className="text-gray-800 leading-relaxed whitespace-pre-wrap font-sans">
                      {record.diagnosis.preliminary}
                    </pre>
                  </div>
                  
                  {record.diagnosis.doctorConfirmed && (
                    <div className="mt-2 text-sm text-gray-600 flex items-center">
                      <User className="w-3 h-3 mr-1" />
                      确认医生：{record.diagnosis.confirmedBy} | 确认时间：{record.diagnosis.confirmedAt}
                    </div>
                  )}
                </div>

                {/* 医生签名区 */}
                <div className="mt-12 pt-6 border-t-2 border-gray-200">
                  <div className="flex justify-between items-end">
                    <div>
                      <p className="text-sm text-gray-600">医生签名：</p>
                      <div className="mt-2 w-32 h-8 border-b border-gray-300"></div>
                    </div>
                    <div className="text-right">
                      <p className="text-sm text-gray-600">日期：{record.visitInfo.date}</p>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </motion.div>

          {/* 底部操作按钮 */}
          <motion.div
            className="mt-8 flex justify-center space-x-4"
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, delay: 0.3 }}
          >
            {isEditing && (
              <Button
                onClick={handleSave}
                className="bg-green-500 hover:bg-green-600 text-white px-6"
              >
                <Save className="w-4 h-4 mr-2" />
                保存修改
              </Button>
            )}
            
            <Button
              onClick={onReturnHome}
              size="lg"
              className="bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white px-8 py-3 rounded-xl shadow-lg"
            >
              完成就诊
            </Button>
          </motion.div>
        </div>
      </div>
    </div>
  );
}